﻿using System.IO;
using System.Windows;
using System.Windows.Browser;
using Microsoft.Silverlight.Testing;
using Microsoft.Silverlight.Testing.Harness.Service;
using Microsoft.Silverlight.Testing.UI;
using Microsoft.Silverlight.Testing.UnitTesting.Harness;
using Microsoft.Silverlight.Testing.UnitTesting.UI;
using Ninject.Core;
using Odin.Contracts.Data;
using Odin.Silverlight.RemoteSessionManager;


namespace Odin.Silverlight
{
	public delegate void TestRunnerReadyEventHandler(UnitTestSettings settings);


	public class TestRunner
	{
		[Inject]
		public IRemoteSessionManager RemoteSessionManager { get; set; }


		private Session _session;

		public void Start(string sessionIdentifier, TestRunnerReadyEventHandler eventHandler)
		{
			RemoteSessionManager.BeginGetSessionByIdentifier(sessionIdentifier,
				a =>
				{
					_session = RemoteSessionManager.EndGetSessionByIdentifier(a);
					var filename = Path.GetFileName(_session.XapPath);
					var actualFile = string.Format("ApplicationToTest/{0}", filename);

					Deployment.Current.Dispatcher.BeginInvoke(
						() =>
							{
								SubApplicationHelper.LoadTestAssemblyFromXapAsync(actualFile,
								(s, e) =>
									{
										var settings = new UnitTestSettings();
										settings.TestHarness = new UnitTestHarness();
										settings.TestService = new SilverlightTestService();

										if (HtmlPage.IsEnabled)
										{
											settings.LogProviders.Add(
												new WebpageHeaderLogProvider(
													"Microsoft.Silverlight.Testing"));
											settings.LogProviders.Add(new UnitTestWebpageLog());
											settings.LogProviders.Add(new TextFailuresLogProvider());

											var resultLogProvider =
												App.Kernel.Get<UnitTestResultLogProvider>();
											resultLogProvider.Session = _session;
											settings.LogProviders.Add(resultLogProvider);
										}

										settings.TestAssemblies.Add(e.Assembly);
										settings.TestHarness.TestHarnessCompleted +=
											TestHarnessCompleted;

										eventHandler(settings);
									}
								);
							});
				}, null);
		}


		void TestHarnessCompleted(object sender, Microsoft.Silverlight.Testing.Harness.TestHarnessCompletedEventArgs e)
		{
			RemoteSessionManager.BeginCompleted(_session, a => RemoteSessionManager.EndCompleted(a), null);

		}

	}

}
